
// FUTURE: Load these from a rest endpoint?
const my_projects = ['TIMER', '6502', 'CHESS', 'SUDOKU', 'CHALLENGES', 'CHOOSER']

// This is an implementation of the Fisher-Yates shuffle
// TODO: Understand this algorithm and credit the Stack Overflow
// post this was copied from
function shuffle(a) {
  for(let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]]
  }
  return a
}

let list = null

window.onload = () => {
  
  const doShuffle = () => {

    const container = document.getElementById('container')
    const main = document.createElement('div')
    const preview = document.getElementById('preview')
    const projects = shuffle([...my_projects])
    while (preview.hasChildNodes())
      preview.removeChild(preview.lastChild)

    // Highlight the first result as the project of the day
    const selected = document.createElement('div')
    selected.classList.add('selected');
    selected.innerText = projects[0];
    projects.shift();
    
    // Display other projects in order
    const li = document.createElement('ul')	
    projects.forEach(i => {
      const p = document.createElement('li')
      p.innerHTML = i
      li.appendChild(p)
    });
    
    if(list) container.removeChild(list)
    main.appendChild(selected)
    preview.appendChild(li)
    main.appendChild(preview)
    container.appendChild(main);
    list = main
  }
  
  const chooseBtn = document.createElement('button')
  chooseBtn.innerHTML = 'Choose My Project!'
  chooseBtn.classList.add('btn')
  chooseBtn.classList.add('btn-primary')
  chooseBtn.onclick  = doShuffle
  
  const chooseArea = document.getElementById('chooseArea')
  chooseArea.appendChild(chooseBtn)

  const li = document.createElement('ul')
  my_projects.forEach(proj => {
    const p = document.createElement('li')
    p.innerHTML = proj
    li.appendChild(p)
  });
  
  const container = document.getElementById('container')
  const preview = document.getElementById('preview')
  
  const header = document.createElement('b')
  header.innerHTML = 'Projects Available'
  preview.appendChild(header)
  preview.appendChild(li)
  container.appendChild(preview)
  list = preview
}
